package com.maoning.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.maoning.common.constant.ProductConstant;
import com.maoning.common.to.SkuHasStockVo;
import com.maoning.common.to.SkuReductionTo;
import com.maoning.common.to.SpuBoundTo;
import com.maoning.common.to.es.SkuEsModel;
import com.maoning.common.utils.R;
import com.maoning.product.entity.*;
import com.maoning.product.feign.CouponFeignService;
import com.maoning.product.feign.SearchFeignService;
import com.maoning.product.feign.WareFeignService;
import com.maoning.product.service.*;
import com.maoning.product.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maoning.common.utils.PageUtils;
import com.maoning.common.utils.Query;

import com.maoning.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private SearchFeignService searchFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
//        1.保存spu基本信息pms_sku_info
        final SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.baseMapper.insert(spuInfoEntity);
//        2.保存spu图片信息pms_spu_info_desc
        final List<String> decript = vo.getDecript();
        final SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        final Long spuInfoEntityId = spuInfoEntity.getId();
        spuInfoDescEntity.setSpuId(spuInfoEntityId);
        spuInfoDescEntity.setDecript(StringUtils.join(decript,","));
        spuInfoDescService.save(spuInfoDescEntity);
//        3.保存spu的图片集pms_spu_images
        final List<String> images = vo.getImages();
        spuImagesService.saveImages(spuInfoEntityId,images);
//        4.保存spu的规则参数pms_product_attr_value
        final List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        if(!CollectionUtils.isEmpty(baseAttrs)){
            final List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(item -> {
                final ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
                productAttrValueEntity.setAttrId(item.getAttrId());
                productAttrValueEntity.setSpuId(spuInfoEntityId);
                final AttrEntity byId = attrService.getById(item.getAttrId());
                productAttrValueEntity.setAttrName(byId.getAttrName());
                productAttrValueEntity.setAttrValue(item.getAttrValues());
                return productAttrValueEntity;
            }).collect(Collectors.toList());
            productAttrValueService.saveBatch(productAttrValueEntities);
        }
//        5.保存spu的积分信息:gulimall_sms -> sms_spu_bounds

        final Bounds bounds = vo.getBounds();
        final SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntityId);
        final R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if(r.getCode() != 0){
            log.error("远程保存spu积分信息失败");
        }
//        5.保存当前spu对应的所有sku信息:

        final List<Skus> skus = vo.getSkus();
        if(!CollectionUtils.isEmpty(skus)){
            skus.forEach(item -> {
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if(image.getDefaultImg() == 1){
                        defaultImg = image.getImgUrl();
                    }
                }
                //        5.1 sku的基本信息pms_sku_info
                final SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
//                private String skuName;
//                private BigDecimal price;
//                private String skuTitle;
//                private String skuSubtitle;
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntityId);
                skuInfoService.save(skuInfoEntity);

                //        5.2 sku的图片信息pms_sku_images
                final Long skuId = skuInfoEntity.getSkuId();
                final List<SkuImagesEntity> skuImagesEntities = item.getImages().stream().map(img -> {
                    final SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> {
                    return StringUtils.isNotEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);
                // 没有图片路径的无需保存
                //        5.3 sku的销售属性信息pms_sku_sale_attr_value
                final List<Attr> attr = item.getAttr();
                final List<SkuSaleAttrValueEntity> attrValueEntities = attr.stream().map(a -> {
                    final SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(attrValueEntities);
                //        5.4 sku的优惠/满减等信息gulimall_sms-> sms_sku_ladder,sms_sku_full_reduction,sms_member_price
                final SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if(skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal(0)) == 1){
                    final R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if(r1.getCode() != 0){
                        log.error("远程保存sku积分信息失败");
                    }
                }
            });
        }
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        final QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        final String key = (String) params.get("key");
        if(StringUtils.isNotEmpty(key)){
            queryWrapper.and((w) -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        final String brandId = (String) params.get("brandId");
        if(StringUtils.isNotEmpty(brandId)&&!"0".equals(brandId)){
            queryWrapper.eq("brand_id", brandId);
        }
        final String catelogId = (String) params.get("catelogId");
        if(StringUtils.isNotEmpty(catelogId)&&!"0".equals(catelogId)){
            queryWrapper.eq("catalog_id", catelogId);
        }
        final String status = (String) params.get("status");
        if(StringUtils.isNotEmpty(status)){
            queryWrapper.eq("publish_status", status);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        List<SkuInfoEntity> list = skuInfoService.getSkuInfosBySpuId(spuId);
        final List<Long> skuIds = list.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //查询sku所有的规格属性,过滤掉不可检索的
        final List<ProductAttrValueEntity> attrValueEntities = productAttrValueService.baseAttrListForSpu(spuId);
        final List<Long> attrIds = attrValueEntities.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        List<Long> searchIds = attrService.selectSearchAttrs(attrIds);
        //给attrid去重
        final HashSet<Long> idSet = new HashSet<>(searchIds);
        //过滤
        List<SkuEsModel.Attr> attrList = new ArrayList<>();
        final List<SkuEsModel.Attr> attrs = attrValueEntities.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(entity -> {
            final SkuEsModel.Attr attr = new SkuEsModel.Attr();
            BeanUtils.copyProperties(entity, attr);
            return attr;
        }).collect(Collectors.toList());

        Map<Long, Boolean> stockMap = null;
        try {
            final R r = wareFeignService.hasStock(skuIds);
            //雷神使用复杂对象的list进行序列化传输~复杂序列化传输
            final TypeReference<List<SkuHasStockVo>> listTypeReference = new TypeReference<List<SkuHasStockVo>>(){};
            final List<SkuHasStockVo> data = r.getData(listTypeReference);
            stockMap = data.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {
            log.error("远程查询库存异常,原因{}", e);
        }

        Map<Long, Boolean> finalStockMap = stockMap;
        final List<SkuEsModel> collect = list.stream().map(skuInfoEntity -> {
            final SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(skuInfoEntity, skuEsModel);
            skuEsModel.setSkuPrice(skuInfoEntity.getPrice());
            skuEsModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());
//            hasStock,hotScore
            //1.发送远程调用,库存查询是否有库存
            //因为循环查库存浪费资源,所以希望有一个方法可以批量查

            if(finalStockMap == null){
                skuEsModel.setHasStock(true);
            }else {
                skuEsModel.setHasStock(finalStockMap.get(skuInfoEntity.getSkuId()));
            }
            //2.热度评分
            skuEsModel.setHotScore(0L);
            //3.查询品牌的名字和分类的名字信息
            final BrandEntity brandEntity = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());

            final CategoryEntity categoryEntity = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());

            //查询sku所有的规格属性,过滤掉不可检索的
            skuEsModel.setAttrs(attrs);

            return skuEsModel;
        }).collect(Collectors.toList());

        // 2021/12/7 5.将所有数据发给es
        final R r = searchFeignService.productStatusUp(collect);
        if(r.getCode() == 0){
//            远程调用成功
            baseMapper.updateSpuStatus(spuId, ProductConstant.SpuStatusEnum.SPU_UP.getCode());
        }else {
//            远程调用失败
        }

    }

    @Override
    public List<SkuItemSaleAttrVo> getSaleAttrsBySpuId(Long spuId) {
        List<SkuItemSaleAttrVo> vos = this.baseMapper.getSaleAttrsBySpuId(spuId);

        return vos;
    }

}